import dayjs from "dayjs";
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const fanyCountdown = (data,wxObj) =>{
  const endYears =Number(dayjs(data).format("YYYY")) ;
  const endMonth =Number(dayjs(data).format("MM"))
  const endDay =Number(dayjs(data).format("DD"))
  const endHour =Number(dayjs(data).format("HH"))
  const endMinutes =Number(dayjs(data).format("mm"))
  const endSeconds =Number( dayjs(data).format("ss"))

  const $app = getApp()
  const newData = $app.globalData.serviceDate||dayjs();
  const years =Number(dayjs(newData).format("YYYY"));
  const month =Number(dayjs(newData).format("MM"))
  const day =Number(dayjs(newData).format("DD"))
  const hour =Number(dayjs(newData).format("HH"))
  const minutes =Number(dayjs(newData).format("mm"))
  const seconds =Number(dayjs(newData).format("ss"))



  let timePoor =(endMonth*30*24*60*60+endDay*24*60*60+ endHour*60*60 +endMinutes*60 + endSeconds) -(month*30*24*60*60+day*24*60*60+ hour*60*60 +minutes*60 + seconds)
  if(timePoor<=0){
    return false;
    clearInterval(wxObj.data.timeInterval)
  }

  const timeInterval= setInterval(()=>{
    const hourPoor = Math.floor(timePoor/(60*60));
    const mintesPoor =Math.floor((timePoor - hourPoor*60*60)/60);
    const secondsPoor=Math.floor((timePoor - hourPoor*60*60 - mintesPoor*60));
    const shutDownTime=[hourPoor<10?`0${hourPoor}`:hourPoor,mintesPoor<10?`0${mintesPoor}`:mintesPoor,secondsPoor<10?`0${secondsPoor}`:secondsPoor]
    wxObj.setData({ shutDownTime})
    if(timePoor<=0){
      clearInterval(wxObj.data.timeInterval);
      wxObj.onPullDownRefresh()
      return false;
    }
    timePoor = timePoor-1
  },1000)
  wxObj.setData({timeInterval})

}


module.exports = {
  formatTime: formatTime,
  fanyCountdown
}
